<?php

namespace app\admin\controller;

use think\Request;
use app\models\Bases;

/**
 * 每日牛股控制器
 * @author wanglong <ycitwl@163.com>
 */
class Shares extends Base
{
	/**
	 * 牛股列表
	 * @return [type] [description]
	 */
	public function sharesShow()
	{
		$shares = new Bases('shares');
		try {
		    $get = input('param.');

            if(!empty($get['searchName']) && empty($get['startTime'])){
                $where['shares_name'] = ['like','%'.$get['searchName'].'%'];
                $result = $shares -> page($where, 'create_time desc', 10);
            }
            if(!empty($get['startTime']) && empty($get['searchName'])){
                $result = $shares -> page(['recommend_time'=> strtotime($get['startTime'])], 'create_time desc', 10);
            }

            if(!empty($get['searchName']) && !empty($get['startTime'])){
                $map['shares_name'] = ['like','%'.$get['searchName'].'%'];
                $map['recommend_time'] = strtotime($get['startTime']);
                $result = $shares -> page($map, 'create_time desc', 10);
            }
            if(empty($get['searchName']) && empty($get['startTime'])){
                $result = $shares -> page('', 'create_time desc', 10);
            }

            if(empty($result)){
                throw new \LogicException('很遗憾，没有数据', 10013);
            }
            return view('sharesList', ['result'=> $result, 'display'=>$get]);
        } catch (\Exception $e) {
		    return self::formatResult($e->getCode(), $e->getMessage());
        }

	}

	/**
	 * 新增牛股
	 * @return [type] [description]
	 */
	public function sharesAdd()
	{
		$sharesModel = new Bases('shares');
		$user = new Bases('admin');
		try{
		    $type_id = empty(input('type_id'))?2:input('type_id');
			if(Request() -> isPost()){
				$post = input('param.');
                $post['type_id'] = $type_id;
				$post['recommend_time'] = strtotime($post['recommend_time']);
				$post['introduce'] = html_entity_decode($post['introduce']);
				$post['create_time'] = time();
				$post['author'] = $user -> value(array('id'=>cookie('login')), 'username');
				//信息必填项
                if(empty($post['shares_name']) || empty($post['introduce']) || empty($post['recommend_time'])){
                    throw new \LogicException('请将页面信息填写完整', 10022);
                }
				//同一推荐日期的牛股至多有四支
                $shares_info = $sharesModel -> selectData(['recommend_time' => $post['recommend_time']], 'order');
                if(count($shares_info) >= 4){
                    throw new \LogicException('该推荐日期内已有四支牛股', 10026);
                }
                //推荐位重复
                foreach($shares_info as $key => $value){
                    if(in_array($post['order'], $value)){
                        throw new \LogicException('推荐位重复', 10027);
                    }
                }
				$result = $sharesModel -> insertData($post);
				if(!$result){
					throw new \LogicException('操作失败', 1);
				}
				return self::formatSuccessResult();
			}
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}
		return view('sharesAdd');
	}

	/**
	 * 编辑保存牛股
	 * @return [type] [description]
	 */
	public function sharesSave()
	{
		$shares_id = intval(input('shares_id'));
		$sharesModel = new Bases('shares');
		$user = new Bases('admin');
		try{
			if(Request() -> isPost()){
				$post = input('param.');
				$post['introduce'] = html_entity_decode($post['introduce']);
				$post['author'] = $user -> value(array('id'=>cookie('login')), 'username');
				$post['recommend_time'] = strtotime($post['recommend_time']);
//				//修改的数据不能为空
                if(empty($post['shares_name']) || empty($post['introduce']) || empty($post['recommend_time'])){
                    throw new \LogicException('若做修改，请将页面信息填写完整', 10022);
                }
                $shares_info = $sharesModel -> find(['shares_id'=>$shares_id]);
                
                $shares_order = $sharesModel -> selectData(['recommend_time' => $post['recommend_time']], 'order');
                //修改了推荐日期
                if($post['recommend_time'] !== intval($shares_info['recommend_time'])){
                	
                    //同一推荐日期至多有四支牛股
                    if(count($shares_order) >= 4){
                        throw new \LogicException('该推荐日期的牛股超过4支', 10026);
                    }
                    foreach($shares_order as $key => $value){
                        if(in_array(intval($post['order']), $value)){
                            throw new \LogicException('推荐位重复', 10027);
                        }
                    }
                } else {
                    //没有修改推荐日期
                    if(intval($post['order']) !== intval($shares_info['order'])){
                        //修改了排序
                        
                        foreach ($shares_order as $key => $value){
                            if(intval($post['order']) === intval($value)){
                                unset($shares_order[$key]);
                            }
                            if(in_array(intval($post['order']), $value)){
                                throw new \LogicException('推荐位重复', 10027);
                            }
                        }
                    }
                }

				$result = $sharesModel -> updateData($post);
				if(!$result){
					throw new \LogicException('未做更新',1);
				}
				return self::formatSuccessResult();
			}
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}		
		$where['shares_id'] = $shares_id;
		$result = $sharesModel->find($where);
		return view('sharesSave', ['result'=>$result]);
	}

	/**
	 * 删除牛股
	 * @return [type] [description]
	 */
	public function sharesDel()
	{
		$shares_id = intval(input('id'));
		$sharesModel = new Bases('shares');
		try{
			$shares_one = $sharesModel->find(" shares_id = ".$shares_id);
			if(empty($shares_one)){
				throw new \LogicException('没找到该数据',1002);
			}
			if(strtotime(date('Y-m-d')) == $shares_one['recommend_time']){
				throw new \LogicException('不能删除当天的数据',1004);
			}
			$result = $sharesModel -> deleteDaPtaByPrimaryKey($shares_id);
			if(!$result){
				throw new \LogicException('操作失败',1);
			}
			return self::formatSuccessResult();
		}catch(\Exception $e){
			return self::formatResult($e->getCode(), $e->getMessage());
		}
	}

}